//
//  PxLoginViewController.m
//  OilCard
//
//  Created by Xu Yefeng on 14-5-18.
//  Copyright (c) 2014年 Free. All rights reserved.
//

#import "PxLoginViewController.h"
#import "LLSSKeychain.h"
#import "PxTabBar.h"
#import "PxTextField.h"

@interface PxLoginViewController ()<PxTabBarDelegate>

@end

@implementation PxLoginViewController {
    NSMutableArray *storeInfo;
    NSString *belongStore;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        storeInfo = [NSMutableArray new];
        belongStore = @"";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setLogoTitleViewWithTitle:@"登录"];
    self.contentView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    
    [self getStoreInfo];
    
    UIImage *bgImg = [UIImage imageNamed:@"Images/login-bg"];
    self.contentView.layer.contents = (id)bgImg.CGImage;
    
    CGFloat height = CGRectGetHeight(self.view.frame);// - [PxGlobal getBaseHeight:NO];
    self.contentView.height = height;
    
    [self.view addSubview:self.contentView];
    
    CGFloat width = CGRectGetWidth(self.view.frame);
    
    CGRect frame = CGRectMake([PxGlobal getCustomerWidth:50], 0, width - [PxGlobal getCustomerWidth:100], 37);
    
    CGFloat top = 90;
    
    UIImageView *image = [UIImageView imageViewWithName:@"Images/logo"];
    image.frame = CGRectMake(0, top, width, 59);
    image.contentMode = UIViewContentModeCenter;
    [self.contentView addSubview:image];
    
    PxTextField *textfield = [[PxTextField alloc] initWithFrame:frame];
    textfield.indent = 12;
    textfield.textColor = [UIColor whiteColor];
    textfield.leftView = [UIImageView imageViewWithName:@"Images/login-user"];
    textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.nameInput = textfield;
    textfield.top = image.bottom + 42.5;
    textfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入登录名"
                                                                      attributes:@{
                                                                                   NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"ffffff"],
                                                                                   NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                                   }
                                       ];
//    textfield.text = @"13588116448";
    [self.contentView addSubview:textfield];
    textfield.delegate = self;
    top = textfield.bottom + 10;

    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(textfield.origin.x, textfield.bottom + 1, textfield.size.width, 1)];
    lineView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:lineView];
    
    textfield = [[PxTextField alloc] initWithFrame:frame];
    textfield.indent = 12;
    textfield.textColor = [UIColor whiteColor];
    textfield.leftView = [UIImageView imageViewWithName:@"Images/login-password"];
    self.pwdInput = textfield;
    textfield.clearButtonMode = UITextFieldViewModeWhileEditing;
    textfield.secureTextEntry = YES;
    textfield.top = top;
    textfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码"
                                                                      attributes:@{
                                                                                   NSForegroundColorAttributeName: [UIColor colorWithHTMLStr:@"ffffff"],
                                                                                   NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                                   }
                                       ];
//    textfield.text = @"123456";
    [self.contentView addSubview:textfield];
    textfield.delegate = self;
    [self.pwdInput linkPreField:self.nameInput];
    
    UIView *lineView2 = [PxGlobal duplicate:lineView];
    lineView2.top = textfield.bottom;
    [self.contentView addSubview:lineView2];
    
    _selectLabel = [[PxClientSelectLabel alloc] initWithFrame:frame AndDelegate:self];
    _selectLabel.top = lineView2.bottom + 10;
    _selectLabel.textColor = [UIColor whiteColor];
    [self.contentView addSubview:_selectLabel];
    _selectLabel.pickerArray = storeInfo;
    _selectLabel.selectDelegate = self;
    
    UIView *lineView3 = [PxGlobal duplicate:lineView];
    lineView3.top = _selectLabel.bottom;
    [self.contentView addSubview:lineView3];
    
    UIButton *button = [PxWidgetCreater customerButton];
    [button setTitleColor:[UIColor colorWithHTMLStr:@"ffffff"] forState:UIControlStateNormal];
    [button setTitle:@"登录"];
    button.frame = frame;
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 10;
//    [button setBackgroundImage:[UIImage imageNamed:@"Images/l-btn"]];
    [button setBackgroundColor:[UIColor colorWithHTMLStr:@"ff4e08"]];
    button.top = lineView3.bottom + 18;
    [self.contentView addSubview:button];
    [button setSelector:@selector(login) withTarget:self];
    
//    UIButton *btn = [PxGlobal duplicate:button];
//    btn.frame = frame;
//    btn.layer.masksToBounds = YES;
//    btn.layer.cornerRadius = 10;
//    [btn setTitle:@"注册"];
//    [btn setSelector:@selector(gotoReg) withTarget:self];
//    btn.top = button.bottom + 10;
//    [self.contentView addSubview:btn];
    
    UIButton *btnReg = [[UIButton alloc] initWithFrame:frame];
    btnReg.backgroundColor = [UIColor clearColor];
    [btnReg setTitle:@"忘记密码?"];
    btnReg.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    [btnReg setSelector:@selector(gotoFindPwd) withTarget:self];
    btnReg.top = button.bottom + 20;
    [self.contentView addSubview:btnReg];
}

-(void)didSelectIndex:(NSInteger)row
{
    NSDictionary *data = _selectLabel.pickerArray[row];
    belongStore = data[@"value"];
}

-(void)getStoreInfo
{
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_DIC_INFO;
    
    [cmd.paramDic addEntriesFromDictionary:@{@"type":@"store"}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        storeInfo = dic[RESULT_DATA];
        [PxGlobal saveData:storeInfo andKey:STORE_INFO];
        _selectLabel.pickerArray = storeInfo;
        [_selectLabel reloadInputViews];
        [_selectLabel setData:0];
        belongStore = storeInfo[0][@"value"];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[RESULT_DESC]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self.nameInput becomeFirstResponder];
    [self autoLogin];
}

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)login
{
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_USER_LOGIN;
    [cmd.paramDic addEntriesFromDictionary:@{@"phone":self.nameInput.text,
                                             @"password":self.pwdInput.text,
                                             @"storeId":belongStore}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:dic[RESULT_DATA]];
        [userInfo setValue:self.nameInput.text forKey:@"phone"];
        [userInfo setValue:self.pwdInput.text forKey:@"password"];
        [userInfo setValue:belongStore forKey:@"storeId"];
        PxUserInfoBean *bean = [PxUserInfoBean beanWithDic:userInfo];
        
        [PxGlobal saveData:userInfo andKey:USER_INFO];
        
//        [LLSSKeychain setPassword:self.pwdInput.text
//                       forService:@"login"
//                          account:self.nameInput.text];
//        
//        [LLSSKeychain setPassword:self.nameInput.text
//                       forService:@"lastLogin"
//                          account:@"lastLogin"];
        
//        [LLAlertService alertWithTip:@"登录成功"];

        [PxNetSession sharedSession].currentUser = bean;
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self replaceViewController:@"PxHomeViewController" withIncomingParam:nil];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[RESULT_DESC]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)autoLogin
{
    NSMutableDictionary *data = [PxGlobal getData:USER_INFO];
    if (!data)
        return;
    NSString *phone = data[@"phone"];
    NSString *password = data[@"password"];
    NSString *storeId = data[@"storeId"];
    
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = TRANS_USER_LOGIN;
    [cmd.paramDic addEntriesFromDictionary:@{@"phone":phone,
                                             @"password":password,
                                             @"storeId":storeId}];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:dic[RESULT_DATA]];
        [userInfo setValue:phone forKey:@"phone"];
        [userInfo setValue:password forKey:@"password"];
        [userInfo setValue:storeId forKey:@"storeId"];
        PxUserInfoBean *bean = [PxUserInfoBean beanWithDic:userInfo];
        
        [PxGlobal saveData:userInfo andKey:USER_INFO];
        
        //        [LLSSKeychain setPassword:self.pwdInput.text
        //                       forService:@"login"
        //                          account:self.nameInput.text];
        //
        //        [LLSSKeychain setPassword:self.nameInput.text
        //                       forService:@"lastLogin"
        //                          account:@"lastLogin"];
        
        //        [LLAlertService alertWithTip:@"登录成功"];
        
        [PxNetSession sharedSession].currentUser = bean;
        [self.navigationController setNavigationBarHidden:NO animated:YES];
        [self replaceViewController:@"PxHomeViewController" withIncomingParam:nil];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService alertWithTip:dic[RESULT_DESC]];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    [LLRestEngine sendCommandRequest:cmd];
}

- (void)setTabbar
{
    
    NSMutableArray *items = [NSMutableArray array];
    
    for (NSString *imageName in @[@"首页.png", @"首页-高亮.png",
                                  //                                  @"提油信息.png", @"提油信息-高亮.png",
                                  @"订单.png", @"订单-高亮.png",
                                  @"下单.png", @"下单-高亮.png",
                                  @"我的.png", @"我的-高亮.png",])
    {
        [items addObject:[NSString stringWithFormat:@"Images/%@", imageName]];
    }
    
    PxTabBar *tabbarView = [[PxTabBar alloc] initWithFrame:CGRectMake(0, self.contentView.bottom, self.view.width, 49)];
    tabbarView.backgroundColor = [UIColor colorWithHTMLStr:@"ebebeb"];
    [tabbarView setImageNameList:items];
    [tabbarView setBtnTitle:@[@"首页", @"订单", @"下单", @"我的"]];
    [self.view addSubview:tabbarView];
    tabbarView.tabDelegate = self;
    
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.view addSubview:lineview];
    lineview.top = tabbarView.top-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"c0c0c0"];
}

- (void)tabSelected:(PxTabBar*)tabbar index:(NSInteger)index
{
    switch (index) {
        case 0:
            [self replaceViewController:@"PxHomeViewController" withIncomingParam:nil];
            break;
        case 1:
            [self replaceViewController:@"PxQueryOrderViewController" withIncomingParam:nil];
            break;
        case 2:
            [self replaceViewController:@"PxPlaceOrderViewController" withIncomingParam:nil];
            break;
        case 3:
            [self replaceViewController:@"PxUserHomeViewController" withIncomingParam:nil];
            break;
            
        default:
            break;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)gotoReg
{
    [self pushViewController:@"PxRegViewController" withIncomingParam:nil];
}

- (void)gotoFindPwd
{
    [self pushViewController:@"PxFindPwdResetViewController" withIncomingParam:nil];
}
//
//- (void)setPwd{
//    
//    // TODO:
//    [self pushViewController:@"PxLockViewController" withIncomingParam:nil];
//    return;
//}
@end
